<template>
  <div class="wrapper">
    <el-card>
      <div class="rowDiv">
        <div class="row-left">
          <div class="row-item">
            <span class="demonstration">时间范围:</span>
            <el-date-picker
              v-model="state.value1"
              type="daterange"
              @change="page_date_fun"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
          <div class="row-item">
            供应商:<el-select
              @change="getOrderlist"
              v-model="state.supplier_id"
              clearable
              placeholder="选择供应商"
            >
              <el-option
                v-for="item in state.supplierArr"
                :label="item.name"
                :value="item.id"
                class="textElps"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="row-item">
            状态:<el-select
              @change="getOrderlist"
              v-model="state.bindstore"
              clearable
              placeholder="选择状态"
            >
              <el-option label="待审核" value="0"> </el-option>
              <el-option label="新采购" value="10"> </el-option>
              <el-option label="履约中" value="20"> </el-option>
              <el-option label="待审核" value="30"> </el-option>
              <el-option label="已完成" value="40"> </el-option>
              <el-option label="已取消" value="99"> </el-option>
            </el-select>
          </div>
          <div class="row-item"></div>
        </div>
        <el-button size="small" type="primary" @click="new_set_order"
          >新建采购</el-button
        >
        <div class="row-right">
          <searchDiv
            :placeholder="state.placeholder"
            @searchClick="searchClick"
          ></searchDiv>
        </div>
      </div>
      <el-table :data="state.tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="pre_id" label="编号"> </el-table-column>
        <el-table-column label="采购清单" width="220">
          <template v-slot="scope">
            <div
              v-for="item in scope.row.item_names"
              class="textElps"
              :key="item"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货/发货/采购">
          <template v-slot="scope">
            <div v-for="item in scope.row.item_counts" :key="item">
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="supplier_name" label="供应商名称">
        </el-table-column>
        <el-table-column align="left" label="费用">
          <template v-slot="scope">
            <div>运费:{{ scope.row.trans_fee }}</div>
            <div>其他费用:{{ scope.row.other_fee }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="imprest" label="预付款"> </el-table-column>
        <el-table-column prop="pay_type" label="结算方式"> </el-table-column>
        <el-table-column prop="note" label="备注"> </el-table-column>
        <el-table-column prop="" label="订单状态"></el-table-column>
        <el-table-column prop="" label="状态信息">
          <template v-slot="scope">
            <div v-for="item in scope.row.info" :key="item">
              {{ item }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <div class="optionDiv">
              <el-button
                @click.native.prevent="editRow(scope.row)"
                type="text"
                size="small"
              >
                完结订单
              </el-button>
              <el-button
                @click.native.prevent="pay_apply(scope.row)"
                type="text"
                size="small"
              >
                付款申请
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Page
        v-if="state.totalPage"
        @changePage="changePage"
        :totalPage="state.totalPage"
      ></Page>
      <!-- 供应商付款申请 -->
      <el-dialog
        title="供应商付款申请"
        v-model="state.new_dialogVisible"
        width="25%"
        center
      >
        <span>
          <el-form
            :model="state.set_form"
            :rules="state.rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="付款金额" prop="pay_amount">
              <el-input v-model="state.set_form.pay_amount"></el-input>
            </el-form-item>
            <el-form-item label="付款类型" prop="pay_type">
              <el-select
                v-model="state.set_form.pay_type"
                placeholder="请选择付款类型"
                clearable
              >
                <el-option label="预付款" value="1"></el-option>
                <el-option label="货款" value="2"></el-option>
                <el-option label="赔付" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="期望时间" prop="exdept_date">
              <el-date-picker
                v-model="state.set_form.exdept_date"
                placeholder="请选择期望时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="申请备注">
              <el-input
                type="textarea"
                v-model="state.set_form.send_note"
              >
              </el-input>
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.new_dialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="create_ware()">提 交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 新建采购单 -->
      <el-drawer
        title="商品采购"
        v-model="state.set_dialogVisible"
        direction="rtl"
        size="50%"
      >
        <div class="conTxt">
          <div class="navTitle">1、选择采购单</div>
          <el-row>
            <el-col :span="8">
              选择采购ID:<el-select
                v-model="state.apply_form.current_id"
                placeholder="请选择"
                clearable
                @change="change_ware_sel"
              >
                <el-option
                  v-for="item in state.apply_form.idArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <div class="navTitle">2、采购清单</div>
          <teble> </teble>
          <el-table :data="state.already_table" border style="width: 100%">
            <el-table-column label="商品名称">
              <template v-slot="scope">
                <el-select
                  @change="change_pro_sel(scope.row, $event)"
                  v-model="scope.row.selected"
                >
                  <el-option
                    v-for="item in scope.row.select_arr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="剩余库存"> </el-table-column>
            <el-table-column label="采购箱数">
              <template v-slot="scope">
                <el-input
                  type="numer"
                  v-model="scope.row.input_count"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="预计单价">
              <template v-slot="scope">
                <el-input type="numer" v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" @click="del(scope.$index)" size="small"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="space-between">
            <el-col :span="12">
              采购合计: {{ send_total_carton || 0 }}箱</el-col
            >
            <el-col :span="12" style="text-align: right"
              ><el-button type="text" @click="addPro"
                >添加商品</el-button
              ></el-col
            >
          </el-row>
          <div class="navTitle">3、采购信息</div>
          <el-form label-width="70px" :inline="true" class="demo-form-inline">
            <el-row>
              <el-col :span="8">
                <el-form-item label="联系人">
                  <el-input
                    v-model="state.apply_form.contact_man"
                    placeholder="联系人"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话">
                  <el-input
                    placeholder="联系电话"
                    v-model="state.apply_form.contact_phone"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发货时间">
                  <el-date-picker
                    type="date"
                    placeholder="预计发货时间"
                    @change="chooseTimeRange"
                    v-model="state.apply_form.send_good_date"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="其他费用">
                  <el-input
                    placeholder="其他费用"
                    v-model="state.apply_form.other_fee"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="付款方式">
                  <el-select
                  @change="pay_type_change"
                    placeholder="付款方式"
                    v-model="state.apply_form.pay_type"
                  >
                    <el-option value="1" label="采购付款" name="当前时间+1小时"
                      ></el-option
                    >
                    <el-option value="2" label="发货付款" name="等于预计发货时间"
                      ></el-option
                    >
                    <el-option value="3" label="到货付款" name="预计发货时间+10天"
                      ></el-option
                    >
                    <el-option value="4" label="完结付款" name="下个月1日"></el-option>
                    <el-option value="5" label="指定日期" name="自选"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="付款时间">
                  <el-date-picker
                    placeholder="付款时间"
                     :disabled="state.apply_form.input_status"
                    v-model="state.apply_form.pay_time"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="预付款">
                  <el-input
                    placeholder="预付款"
                    v-model="state.apply_form.advance"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="运费">
                  <el-input
                    placeholder="运费"
                    v-model="state.apply_form.trans_fee"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="预计付款时间" label-width="100px">
                  <el-date-picker
                    placeholder="预计付款时间"
                    @change="advanceChange"
                    v-model="state.apply_form.advance_pay_time"
                  ></el-date-picker>
                </el-form-item>
                
              </el-col>
            </el-row>
            <div class="navTitle">4、备注</div>
            <el-input type="textarea" v-model="state.apply_form.supplier_note">
            </el-input>
            <el-row> </el-row>
          </el-form>
          <el-row type="flex" justify="center" style="margin-top: 20px">
            <el-col :span="4"><el-button @click="state.set_dialogVisible=false;">取消</el-button></el-col>
            <el-col :span="4"
              ><el-button type="primary" @click="onSubmit"
                >创 建</el-button
              ></el-col
            >
          </el-row>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import {
  ref,
  computed,
  onMounted,
  watch,
  reactive,
  getCurrentInstance,
} from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import searchDiv from "@/components/Search.vue";
import Page from "@/components/Pagination.vue";
export default {
    name:"purchase_request",
  components: { searchDiv, Page },
  props: {},
  setup() {
    let form = ref("null");

    const double = computed(() => {
      let total_price = 0;
      let storage_total = 0;
      let data = state.good_data;
      // 数量*箱规*价格
      data.forEach((v) => {
        total_price +=
          Number(parseFloat(v.input_residue)) *
          Number(parseFloat(v.carton)) *
          Number(parseFloat(v.input_unit_price));
      });
      storage_total +=
        total_price + Number(state.storage_fee) + Number(state.other_fee);
      return { total_price, storage_total };
    });
    // 收货里的计算属性
    const sum_num = computed(() => {
      let total = 0;
      state.receiveData.filter((v) => {
        total += Number(v.unit_price);
      });
      return total;
    });
    // 采购合计
    const send_total_carton = computed(() => {
      let total = 0;
      state.already_table.filter((v) => {
        total += Number(v.input_count);
      });
      return total;
    });
    const { ctx } = getCurrentInstance();
    let state = reactive({
      temp_data: [], //顶部下拉切换底部数据暂存
      supplier_id: "",
      supplierArr: [],
      common_id: "",
      already_table: [], //新建发货单的表格
      set_form: {
        current_id: "",
        pay_amount:"",
        exdept_date:"",
        idArr: "",
        send_good_total: 0,
        contact_man: "",
        contact_phone: "",
        send_good_date: "",
        recieve_good_ware: "",
        recieve_good_arr: [],
        pay_type: "",
        log_num: "",
        advance: "",
        recieve_phone: "",
        send_pro_fee: "",
        send_other_fee: "",
        send_note: "",
      },
      orderObj: {
        send_order: "",
        orderdataArr: [], //发货单数组
        for_inware: "",
        for_inwareArr: [], //入库仓库
      },
      edit_form: {
        transfee: "",
        otherFee: "",
        trans_type: "",
        trans_num: "",
        expect_date: "",
      },
      recive_dialogVisible: false,
      set_dialogVisible: false,
      total_recive_cartons: 0,
      send_good_fee: 0,
      other_good_fee: 0,
      recieve_note: "",
      storage_fee: 0,
      other_fee: 0,
      storage_note: "",
      new_dialogVisible: false,
      common_id: "",
      num: "",
      waretype: "",
      value1: "",
      begin_date: "",
      end_date: "",
      keywords: "",
      placeholder: "请输入您要搜索的内容",
      searchval: "",
      page: 1,
      totalPage: "",
      noteTxt: "",
      note_dialogVisible: false,
      order_dialogVisible: false,
      bindstore: "",
      good_data: [],
      receiveData: [],
      apply_form: {
        advance:'',
        idArr:[],
        send_good_date:'',
        current_id:'',
        other_fee:"",
        pay_amount: "",
        ware_name: "",
        pay_type: "",
        pay_time:"",
        pay_type_arr: [],
        exdept_date: "",
        contact_man: "",
        contact_phone: "",
        ware_address: "",
        supplier_note: "",
        advance_pay_time:'',
        trans_fee:'',
        input_status:false
      },
      rules: {
        pay_amount: [
          { required: true, message: "请填写付款金额", trigger: "blur" },
        ],
        ware_name: [
          { required: true, message: "请填写仓库名称", trigger: "blur" },
        ],
        pay_type: [
          { required: true, message: "请选择付款类型", trigger: "change" },
        ],
        exdept_date: [
          { required: true, message: "请选择期望时间", trigger: "change" },
        ],
        contact_man: [
          { required: true, message: "请填写联系人", trigger: "blur" },
        ],
        contact_phone: [
          { required: true, message: "请填写联系电话", trigger: "blur" },
        ],
        ware_address: [
          { required: true, message: "请填写仓库地址", trigger: "blur" },
        ],
      },
      tableData: [],
    });
    // 搜索事件
    function searchClick(searchCon) {
      state.keywords = searchCon;
      getOrderlist();
    }
    // 确认收货
    function confirm_recieve() {
      let data = state.receiveData;
      let items = [];
      data.forEach((v) => {
        let obj = {
          id: v.id,
          count: v.count,
        };
        items.push(obj);
      });
      ctx.$http
        .post("/tanxiaji/supplier/delivery/receive/", {
          delivery_id: state.common_id,
          transport_fee: state.send_good_fee,
          other_fee: state.other_good_fee,
          note: state.recieve_note,
          items: JSON.stringify(items),
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.recive_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 编辑
    function editRow(item) {
      state.common_id = item.id;
      state.edit_form.transfee = "";
      state.edit_form.otherFee = "";
      state.edit_form.trans_type = "";
      state.edit_form.trans_num = "";
      state.edit_form.expect_date = "";
      state.order_dialogVisible = true;
      state.edit_form.transfee = item.trans_fee;
      state.edit_form.otherFee = item.other_fee;
      state.edit_form.trans_type = item.trans_method;
      state.edit_form.trans_num = item.trans_number;
      state.edit_form.expect_date = item.deliver_eta;
    }
    // 更改数量
    function changeResidue(item) {
      let current = item.input_residue;
      let origin_num = item.residue;
      if (current < 1) {
        item.input_residue = 1;
      }
      if (current > origin_num) {
        item.input_residue = item.residue;
      }
    }
    // 移除
    function deleteRow(idx) {
      console.log(idx);
      state.good_data.splice(idx, 1);
    }
    // 修改备注
    function show_note(item) {
      state.note_dialogVisible = true;
      state.common_id = item.row.id;
      state.num = item.row.pre_id;
      if (item.row.note) {
        state.noteTxt = item.row.note;
      } else {
        state.noteTxt = "";
      }
    }
    // 提交新建入库单
    function submitForm() {
      let arr = state.good_data;
      let items = [];
      arr.forEach((v) => {
        let obj = {
          id: v.id,
          count: v.input_residue,
          unit_price: v.input_unit_price,
        };
        items.push(obj);
      });
      let data = {
        receive_id: state.orderObj.send_order || "",
        warehouse_id: state.orderObj.for_inware,
        inbound_fee: state.storage_fee,
        other_fee: state.other_fee,
        note: state.storage_note,
        items: JSON.stringify(items),
        amount: double.value.total_price,
      };
      if (!items.length) return ElNotification.error("请选择商品");

      ctx.$http
        .post("/tanxiaji/supplier/inbound/create/", data)
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.order_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 分页
    function changePage(e) {
      state.page = e;
      getOrderlist();
    }
    // 编辑完成
    function allow_order() {
      ctx.$http
        .post("/tanxiaji/supplier/delivery/edit/", {
          deliver_id: state.common_id,
          transport_fee: state.edit_form.transfee,
          other_fee: state.edit_form.otherFee,
          transport_method: state.edit_form.trans_type,
          transport_number: state.edit_form.trans_num,
          deliver_eta: state.edit_form.expect_date,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.order_dialogVisible = false;
            ElNotification.success(res.errmsg);
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 获取仓库
    function getWarelist() {
      ctx.$http
        .get("/tanxiaji/erp/depot/ajax/search/", {
          type: 1,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.wareArr = res.data;
            state.orderObj.for_inwareArr = res.data;
            state.set_form.recieve_good_arr = res.data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 获取新建入库单的仓库列表
    function get_order_ware() {
      ctx.$http
        .post("/tanxiaji/supplier/receive/short/", {})
        .then((res) => {
          if (res.errno == 0) {
            state.orderObj.orderdataArr = res.data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 更改发货单号获取对应的商品
    function change_send_order() {
      let current_order_id = state.orderObj.send_order;
      if (!current_order_id) return;
      let order_items = state.orderObj.orderdataArr.filter(
        (v) => v.id == current_order_id
      )[0].items;
      console.log(order_items);
      order_items.filter((v) => {
        v["input_residue"] = JSON.parse(JSON.stringify(v.residue));
        v["input_unit_price"] = JSON.parse(JSON.stringify(v.unit_price));
      });
      console.log(order_items);
      state.good_data = [...order_items];
    }
    // 关闭弹窗--并清除表单信息
    function new_set_inware() {
      state.new_dialogVisible = true;
      get_order_ware();
      state.orderObj.send_order = "";
      state.orderObj.for_inware = "";
      state.good_data = [];
      state.storage_fee = 0;
      state.other_fee = 0;
      state.storage_note = "";
    }
    // 时间范围取值格式化
    function page_date_fun(e) {
      if (e != null) {
        state.begin_date = dayjs(e[0]).format("YYYY-MM-DD");
        state.end_date = dayjs(e[1]).format("YYYY-MM-DD");
      } else {
        state.begin_date = "";
        state.end_date = "";
      }
      getOrderlist();
    }
    // 时间范围取值格式化
    function chooseTimeRange(e) {
      if (e != null) {
        state.set_form.send_good_date = dayjs(e).format("YYYY-MM-DD");
        state.apply_form.send_good_date = dayjs(e).format("YYYY-MM-DD");
      } else {
        state.set_form.send_good_date = "";
        state.apply_form.send_good_date = "";
      }
    }
    function advanceChange(e){
if (e != null) {
        state.apply_form.advance_pay_time = dayjs(e).format("YYYY-MM-DD");
      } else {
        state.apply_form.advance_pay_time= "";
      }
    }
    // 付款申请提交
    function create_ware() {
      alert("需要调接口");
      form.value.validate((valid) => {
        if (valid) {
          ctx.$http
            .post("", {
              procure_id: 119,
              payMoney: state.set_form.pay_amount,
              payType: state.set_form.pay_type,
              exceptData: state.set_form.exdept_date,
              applyNote: state.set_form.send_note,
            })
            .then((res) => {
              if (res.errno == 0) {
                ElNotification.success(res.errmsg);
                state.new_dialogVisible = false;
                getOrderlist();
              } else {
                ElNotification.error(res.errmsg);
              }
            })
            .catch((err) => {
              ElNotification.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
    onMounted(() => {
      getOrderlist();
      getWarelist();
      get_supplier_ajax();
    });
    // 审批
    function approveBtn(item) {
      ElMessageBox.confirm(
        `是否让编号为${item.row.pre_id}的订单通过审核？`,
        "提示",
        {
          confirmButtonText: "通过审核",
          cancelButtonText: "拒绝通过",
          distinguishCancelAndClose: true,
          type: "warning",
          center: true,
        }
      )
        .then((action) => {
          console.log(action);
          approveAjax(item.row.id, 20);
        })
        .catch((action) => {
          console.log(action);
          if (action == "cancel") {
            approveAjax(item.row.id, 10);
          }
        });
    }
    // 审核的接口
    function approveAjax(id, type) {
      ctx.$http
        .post("/tanxiaji/supplier/inbound/verify/", {
          inbound_id: id,
          verify_type: type,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 付款申请
    function pay_apply(item) {
      state.new_dialogVisible = true;
      state.common_id = item.id;
    }
    // 发货
    function cancle_order(item) {
      ctx.$http
        .post("/tanxiaji/supplier/delivery/deliver/", {
          delivery_id: item.id,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 收货弹窗
    function recive_order(item) {
      state.common_id = item.id;
      ctx.$http
        .post("/tanxiaji/supplier/delivery/detail/", {
          delivery_id: item.id,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.recive_dialogVisible = true;
            state.receiveData = res.data.items;
            state.recieve_note = res.data.note;
            state.send_good_fee = res.data.transport_fee;
            state.other_good_fee = res.data.other_fee;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    //获取页面信息
    function getOrderlist() {
      ctx.$http
        .post("/tanxiaji/supplier/procure/manage/", {
          supplier_id: state.supplier_id,
          page: state.page,
          keyword: state.keywords || "",
          status: state.bindstore,
          start_date: state.begin_date,
          end_data: state.end_date,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.tableData = res.data.procures;
            state.apply_form.pay_type_arr = res.data.pay_methods;
            state.totalPage = res.data.pages;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 提交备注修改
    function sub_note() {
      ctx.$http
        .post("/tanxiaji/supplier/erp/oreder/note_info/", {
          num: state.num,
          note: state.noteTxt,
          type_no: 4,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.note_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 新建采购
    function new_set_order() {
      state.apply_form.current_id = "";
      state.already_table = [];
      state.set_dialogVisible = true;
      state.apply_form.contact_man = ""; //发货人
      state.apply_form.contact_phone = ""; //联系电话
      state.apply_form.send_good_date = ""; 
      state.apply_form.other_fee = "";
      state.apply_form.pay_type = "";
      state.apply_form.pay_time = "";
      state.apply_form.advance = "";
      state.apply_form.advance_pay_time = "";
      state.apply_form.trans_fee = "";
      state.apply_form.supplier_note = "";
      ctx.$http
        .post("/tanxiaji/supplier/list/short/")
        .then((res) => {
          if (res.errno == 0) {
            let data = res.data;
            state.apply_form.idArr = data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 获取供应商
    function get_supplier_ajax() {
      ctx.$http
        .post("/tanxiaji/supplier/list/short/", {})
        .then((res) => {
          if (res.errno == 0) {
            state.supplierArr = res.data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 改变顶部下拉框
    function change_ware_sel(e) {
      state.already_table = [];
      state.temp_data = [];
      let id = state.apply_form.current_id; //当前顶部仓库勾选的
      get_pro_item(id);
    }
    // 修改商品的下拉
    function change_pro_sel(item, e) {
      console.log("当前项", item, e);
      let currnt_m_id = e;
      let origin = state.temp_data;
      console.log("origin", origin);
      let current_chose = origin.filter((v) => v.id == e)[0];
      console.log("对应下拉数据", current_chose);
      item.carton = current_chose.carton;
      item.input_count = 0;
      item.id = current_chose.id;
      item.price = current_chose.price;
      item.stock = current_chose.stock;
    }
    // 获取对应的items,并添加到数组里
    function get_pro_item(top_id) {
      ctx.$http
        .post("/tanxiaji/supplier/goods/", {
          supplier_id: top_id,
        })
        .then((res) => {
          if (res.errno == 0) {
            let data = res.data;
            state.temp_data = JSON.parse(JSON.stringify(data));
            let items = [];
            if (!data.length) return;
            data.forEach((v) => {
              let obj = {
                id: v.id,
                name: v.name,
              };
              items.push(obj);
            });
            console.log("items", items);
            let obj = {
              input_count: 0,
              selected: data[0].id,
              carton: data[0].carton,
              stock: data[0].stock,
              price: data[0].price,
              select_arr: items,
            };
            state.already_table.push(obj);
            console.log("菜单里", state.already_table);
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 添加商品
    function addPro() {
      let current_top_id = state.apply_form.current_id;
      console.log(current_top_id);
      get_pro_item(current_top_id);
    }
    // 删除商品item
    function del(idx) {
      state.already_table.splice(idx, 1);
    }
    // 切换收货仓库--变更收货人和电话
    function recieve_ware_change(e) {
      let data = state.set_form.recieve_good_arr.filter(
        (v) => v.warehouse_id == e
      )[0];
      state.set_form.advance = data.contacts;
      state.set_form.recieve_phone = data.contacts_phone;
    }
    // 提交采购
    function onSubmit() {
      let data = state.already_table;
      let items = [];
      data.forEach((v) => {
        let obj = {
          id: v.id,
          count: v.input_count,
          unit_price: v.price,
        };
        items.push(obj);
      });
      let ot = {
        supplier_id: state.apply_form.current_id, //顶部采购id
        liaison: state.apply_form.contact_man,
        phone: state.apply_form.contact_phone,
        deliver_eta: state.apply_form.send_good_date,
        imprest: state.apply_form.advance, //预付款
        pay_method: state.apply_form.pay_type,
        pay_eta: state.apply_form.advance_pay_time,
        transport_fee: state.apply_form.trans_fee,
        other_fee: state.apply_form.other_fee,
        pay_time:state.apply_form.pay_time,
        note: state.apply_form.supplier_note,
        items: JSON.stringify(items),
      };
      console.log(ot);
      ctx.$http
        .post("/tanxiaji/supplier/procure/create/", ot)
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.set_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 付款方式更改
    function pay_type_change(e){
      let time_s = new Date().getTime();//当前时间的时间戳
      let YFa_time=dayjs(state.set_form.send_good_date).format()
      let YFa_time_s=new Date(YFa_time).getTime();
         if(e==1){  // 采购付款 = 当前时间 + 1小时
                let t=time_s + 1000 * 60 * 60;//设置新时间比旧时间多一小时
                let time=timestampToTime(t);
              state.apply_form.input_status=true;
              state.apply_form.pay_time=time;
            }else if(e==2){ // 发货付款 = 预计发货时间
                if(state.set_form.send_good_date==''){
                    ElNotification.error("预计发货时间不能为空！");
                    state.apply_form.input_status=false;
                    state.apply_form.pay_type='';
                    state.apply_form.pay_time='';
                    return
                }
                state.apply_form.pay_time=state.set_form.send_good_date;
                state.apply_form.input_status=true;
            }else if(e==3){ // 到货付款 = 预计发货时间 + 10天
                if(state.set_form.send_good_date==''){
                   ElNotification.error("预计发货时间不能为空！");
                    state.apply_form.input_status=false;
                     state.apply_form.pay_type='';
                    state.apply_form.pay_time='';
                    return 
                }
                var t=YFa_time_s + 1000 * 60 * 60 * 24 * 10;//设置新时间比旧时间多一小时
                var time=timestampToTime(t);
                time=new Date(time);
                var y=time.getFullYear();////获取完整的年份(4位,1970-????)
                var m=time.getMonth()+1; //获取当前月份(0-11,0代表1月)
                var d=time.getDate();        //获取当前日(1-31)
                if(m<10){
                    m='0'+m;
                }if(d<10){
                    d='0'+d;
                }
                time=y+"-"+m+"-"+d
                state.apply_form.pay_time=time;
                state.apply_form.input_status=true;
            }else if(e==4){ // 完结付款 = 下月一日
                let Year = new Date().getFullYear();    //获取完整的年份(4位,1970-????)
                let Month = new Date().getMonth() + 1;       //获取当前月份(0-11,0代表1月)
                // Month=9  //测试  给月份赋值
               if(Month<9){   //  如果当前月份小于9   那么应输出的月份就是 0？
                   Month=Month+1;
                   var time=Year+'-0'+Month+'-01';
                }else if(Month>=9 && Month<12){  //  如果当前月份大于等于9且小于12    那么应输出的月份就是 1？
                   Year=Year+1;
                   Month=Month+1;
                   var time=Year+'-'+Month+'-01';
               }else if(Month==12){  //  如果当前月份等于12   那么应输出的月份就是 01 月； 年份加1
                    Year=Year+1;
                    Month=1;
                    var time=Year+'-0'+Month+'-01';
                }
                state.apply_form.pay_time=time;
               state.apply_form.input_status=true;
            }else{  // 指定日期 (自选)
                 state.apply_form.input_status=false;
                 state.apply_form.pay_time='';
            }
    }
     //将时间戳转换成日期格式：
        function timestampToTime(timestamp) {
            var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            var D = date.getDate() + ' ';
            var h = date.getHours() + ':';
            var m = date.getMinutes() + ':';
            var s = date.getSeconds();
            return Y+M+D+h+m+s;
        };
    return {
      pay_type_change,
      pay_apply,
      onSubmit,
      recieve_ware_change,
      del,
      send_total_carton,
      change_ware_sel,
      new_set_order,
      sum_num,
      editRow,
      sub_note,
      approveBtn,
      searchClick,
      form,
      state,
      new_set_inware,
      close,
      create_ware,
      allow_order,
      chooseTimeRange,
      getWarelist,
      getOrderlist,
      changePage,
      show_note,
      change_send_order,
      double,
      changeResidue,
      deleteRow,
      submitForm,
      cancle_order,
      recive_order,
      confirm_recieve,
      change_pro_sel,
      addPro,
      page_date_fun,
      advanceChange
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  .el-card {
    height: 100%;
    .cart-title::before {
      content: " ";
      width: 4px;
      height: 20px;
      background: #1890ff;
      background: #1890ff;
      display: inline-block;
      vertical-align: middle;
      margin-right: 5px;
    }
    .rowDiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .row-left {
        display: flex;
        width: 70%;
        justify-content: space-between;
        .row-item {
          display: flex;
          align-items: center;
          white-space: nowrap;
        }
      }
      .row-right {
        width: 15%;
        display: flex;
        justify-content: flex-end;
      }
    }
    .el-table /deep/ th {
      background-color: #eaeaea;
      text-align: center;
    }
    .el-table /deep/ td {
      text-align: center;
    }
  }
  .conTxt {
    padding: 0 20px;
  }
  .optionDiv {
    display: flex;
    justify-content: center;
  }
}
</style>